<?php

class LoginController extends Site_Controller_Action {

    public function init() {
        /* Initialize action controller here */
    }

    public function indexAction() {
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/login.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskedinput.min.js');
    
        
        $this->view->titulo = 'Efetue o login ou cadastre-se para continuar.';

        $form = new Application_Form_Login();
        $this->view->form_login = $form;

        $form2 = new Application_Form_Cadastro();
        $this->view->form_cad = $form2;
        
    }

    public function loginAction() {
        Zend_Loader::loadClass('usuario','library');
        Zend_Loader::loadClass('auth','library');
        //$this->_helper->layout->disableLayout(); 
        //$this->_helper->viewRenderer->setNoRender(); 
        $this->_helper->viewRenderer->setRender('index');

        $form = new Application_Form_Cadastro();
        $this->view->form_cad = $form;

        $this->_flashMessenger = $this->_helper->getHelper('FlashMessenger');
        $this->view->messages = $this->_flashMessenger->getMessages();
        $form = new Application_Form_Login();

        $this->view->form_login = $form;
        
        if ($this->getRequest()->isPost()) {
            $data = $this->getRequest()->getPost();
            //Formulário corretamente preenchido?
            if ($form->isValid($data)) {
                
                
                $login = $form->getValue('log_login');
                $senha = $form->getValue('log_senha');

                $dbAdapter = Zend_Db_Table::getDefaultAdapter();
                //Inicia o adaptador Zend_Auth para banco de dados
                $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
                $authAdapter->setTableName('USUARIOS')
                        ->setIdentityColumn('USU_LOGIN')
                        ->setCredentialColumn('USU_SENHA')
                        ->setCredentialTreatment('SHA1(?)');

                //Define os dados para processar o login
                $authAdapter->setIdentity($login)
                        ->setCredential($senha);

                //Efetua o login
                $auth = Zend_Auth::getInstance();
                $result = $auth->authenticate($authAdapter);
                //Verifica se o login foi efetuado com sucesso
                if ($result->isValid()) {
                    $info = $authAdapter->getResultRowObject(null, 'USU_SENHA');
                    $storage = $auth->getStorage();
                    $storage->write($info);
                    if(Usuario::ValidarStaCad($storage->read()->USU_ID) == 1){
                        Zend_Auth::getInstance()->clearIdentity();
                        echo '<script>alert("Confirme seu cadastro atraves do e-mail de ativacao para acessar sua conta!"); location.href = "'.$this->_urlbase.'/login";</script>';
                        exit;
                    }
                    
                    // valida status do usuário
                    
                    if(!Usuario::ValidarStaUsu($storage->read()->USU_ID)){
                        Zend_Auth::getInstance()->clearIdentity();
                        //Dados inválidos
                        //$this->_helper->FlashMessenger('Usuário ou senha inválidos!');
                        //return $this->_helper->redirector('index', 'index', array());
                        echo '<script>alert("Usuário ou senha incorretos!");</script>';
                    }else{
                    
                        Usuario::setIdSessaoUsu($storage->read()->USU_ID, session_id());

                        auth::montaSessao($auth,$authAdapter);

                        $sessao = new Zend_Session_Namespace('retorno');
                        $controler = $sessao->controler;
                        $action = $sessao->action;
                        $id = $sessao->id; 
                        $sessao->controler = '';
                        $sessao->action = '';
                        $sessao->id = '';
                        if(strlen($id) <= 0)$this->_helper->redirector($action, $controler, array());
                        $this->_helper->redirector($action, $controler,$module,array('id'=>$id));
                    }
                }else{
                    echo '<script>alert("Usuário ou senha incorretos!");</script>';
                }
            }
        }
    }

    public function cadastroAction() {
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/login.js?1=1');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskedinput.min.js');
        
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('auth','library');
        //$this->_helper->layout->disableLayout(); 
        //$this->_helper->viewRenderer->setNoRender(); 
        $this->_helper->viewRenderer->setRender('index');

        $form = new Application_Form_Login();
        $this->view->form_login = $form;

        $form = new Application_Form_Cadastro();

        $this->view->form_cad = $form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            try {
                if($form->isValid($formData)) {
                    $id = (int) $form->getValue('USU_ID',0);
                    $data = array(
                        //'USU_ID'        => $form->getValue('USU_ID'),
                        'USU_EMAIL' => $form->getValue('cad_email'),
                        'USU_LOGIN' => $form->getValue('cad_login'),
                        'USU_CPF' => $form->getValue('cad_cpf'),
                        'USU_NOME' => $form->getValue('cad_nome'),
                        'PER_ID' => 5, // permissão alunos
                        'USU_DTCADASTRO' => date('Y-m-d'),
                        'USU_TPO' => 2, // 2 = alunos
                        'USU_SENHA' => sha1($form->getValue('cad_senha')),
                        'USU_CADSTA' => 1,
                        'USU_STA' => 1,
                        'USU_DTNASC'    => Datetools::dma_amd($form->getValue('cad_datnasc')),
                        'USU_CEP'       => $form->getValue('cad_cep'),
                        'USU_ENDERECO'  => $form->getValue('cad_endereco'),
                        'USU_BAIRRO'    => $form->getValue('cad_bairro'),
                        'USU_CIDADE'    => $form->getValue('cad_cidade'),
                        'USU_UF'        => $_REQUEST['uf'],
                        'USU_TEL'       => $form->getValue('cad_tel'),
                        'USU_PER1'       => $form->getValue('cad_per1'),
                        'USU_PER2'       => $form->getValue('cad_per2'),
                        'USU_PER3'       => $form->getValue('cad_per3'),
                        'USU_STAEML'     => 1,

                    );

                    $obj = new Ead_Model_DbTable_Usuarios();

                    if ($id == 0){
                        $obj->insert($data);
                        $id =  $obj->getAdapter()->lastInsertId();
                    }
                    
                    /*
                    $dbAdapter = Zend_Db_Table::getDefaultAdapter();
                    //Inicia o adaptador Zend_Auth para banco de dados
                    $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
                    $authAdapter->setTableName('USUARIOS')
                            ->setIdentityColumn('USU_LOGIN')
                            ->setCredentialColumn('USU_SENHA')
                            ->setCredentialTreatment('SHA1(?)');

                    //Define os dados para processar o login
                    $authAdapter->setIdentity($form->getValue('cad_login'))
                            ->setCredential($form->getValue('cad_senha'));

                    //Efetua o login
                    $auth = Zend_Auth::getInstance();
                    $result = $auth->authenticate($authAdapter);

                    $info = $authAdapter->getResultRowObject(null, 'USU_SENHA');
                    $storage = $auth->getStorage();
                    $storage->write($info);


                    // valida status do usuário
                    Zend_Loader::loadClass('usuario','library');
                    if(!Usuario::ValidarStaUsu($storage->read()->USU_ID)){
                        //Dados inválidos
                        $this->_helper->FlashMessenger('Usuário ou senha inválidos!');
                        return $this->_helper->redirector('index', 'index', array());
                    }

                    Usuario::setIdSessaoUsu($storage->read()->USU_ID, session_id());


                    auth::montaSessao($auth,$authAdapter);
                    */
                    // envia email cadastro
                    $arr['email'] = $form->getValue('cad_email');
                    $arr['nome'] = $form->getValue('cad_nome');
                    $arr['login'] = $form->getValue('cad_login');
                    $arr['senha'] = $form->getValue('cad_senha');
                    $arr['urlbase']   = $this->_urlbase;
                    $arr['usu_id']  = $id;
                    Zend_Loader::loadClass('envioemail','library');
                    envioemail::Cadastro($arr);
                    
                    $form->reset();
                    
                    /*
                    $sessao = new Zend_Session_Namespace('retorno');
                    $controler = $sessao->controler;
                    $action = $sessao->action;
                    $id = $sessao->id; 
                    $sessao->controler = '';
                    $sessao->action = '';
                    $sessao->id = '';
                    if(strlen($id) <= 0)$this->_helper->redirector($action, $controler, array());
                    else $this->_helper->redirector($action, $controler,$module,array('id'=>$id));
                    */
                    
                    return $this->_helper->redirector('sucesso', 'login', array());

                    //echo 'cadastro realizado';
            
                } else {
                    $form->populate($formData);
                }
            } catch(Exception $ex) {
                Zend_Loader::loadClass('errordb','library');
                echo '<script>alert("'.Errordb::descricaoError($ex->getCode()).'");</script>';
                //echo $ex->getCode().'<br>';       
                //echo $ex->getMessage().'<br>';
                $form->populate($formData);
            }
        }
    }
    public function loginajxAction() {
        Zend_Loader::loadClass('usuario','library');
        Zend_Loader::loadClass('auth','library');
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender(); 
        $this->_helper->viewRenderer->setRender('login');
   
        
        if ($this->getRequest()->isPost()) {
            $data = $this->getRequest()->getPost();
            //Formulário corretamente preenchido?
            $login = $this->_getParam('usuario', 0);
            $senha = $this->_getParam('senha', 0);
                
            if (strlen($login) > 0 && strlen($senha) > 0) {

                $dbAdapter = Zend_Db_Table::getDefaultAdapter();
                //Inicia o adaptador Zend_Auth para banco de dados
                $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
                $authAdapter->setTableName('USUARIOS')
                        ->setIdentityColumn('USU_LOGIN')
                        ->setCredentialColumn('USU_SENHA')
                        ->setCredentialTreatment('SHA1(?)');

                //Define os dados para processar o login
                $authAdapter->setIdentity($login)
                        ->setCredential($senha);

                //Efetua o login
                $auth = Zend_Auth::getInstance();
                $result = $auth->authenticate($authAdapter);
                //Verifica se o login foi efetuado com sucesso
                if ($result->isValid()) {
                    $info = $authAdapter->getResultRowObject(null, 'USU_SENHA');
                    $storage = $auth->getStorage();
                    $storage->write($info);
                    
                    if(Usuario::ValidarStaCad($storage->read()->USU_ID) == 1){
                        Zend_Auth::getInstance()->clearIdentity();
                        echo json_encode(array('ok' => FALSE, 'msg' => 'Confirme seu cadastro através do e-mail de ativação para acessar sua conta!'));
                        exit;
                    }
                    
                    // valida status do usuário
                    Zend_Loader::loadClass('usuario','library');
                    if(!Usuario::ValidarStaUsu($storage->read()->USU_ID)){
                        //Dados inválidos
                        //$this->_helper->FlashMessenger('Usuário ou senha inválidos!');
                        //return $this->_helper->redirector('index', 'index', array());
                         echo json_encode(array('ok' => FALSE, 'msg' => 'Usuário ou senha incorretos!')); 
                         exit;
                    }

                    Usuario::setIdSessaoUsu($storage->read()->USU_ID, session_id());
                    
                    auth::montaSessao($auth,$authAdapter);
                    //$script = '<script>location.href="'.$this->_urlbase.'/ead";</script>';
                    $script = '<script>location.href="'.$this->_urlbase.'";</script>';
                    $html = '<a href="/neneco/ead/">Acessar Sistema EAD</a><a href="/neneco/login/logout">Sair</a>'.$script;
                    
                    echo json_encode(array('ok' => TRUE, 'html'=>$html));
                    
                }
                else{
                    echo json_encode(array('ok' => FALSE, 'msg' => 'Usuário ou senha incorretos!'));  
                }
            }
            else{
                echo json_encode(array('ok' => FALSE, 'msg' => 'Usuário ou senha incorretos!'));  
            }
        }    
        
    }
    public function logoutAction() {
        //Limpa dados da Sessão
        Zend_Auth::getInstance()->clearIdentity();

        return $this->_helper->redirector('index', 'index', array());
    }
    
    public function sucessoAction() {
        //if (!Zend_Auth::getInstance()->hasIdentity() && empty(Zend_Auth::getInstance()->getStorage()->read()->USU_LOGIN)){
        //    return $this->_helper->redirector('', 'login', array());
        //}
    }
    
    public function valemailAction(){
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender(); 
        
        $email = $this->_getParam('email', FALSE);
        
        if($email != FALSE && strlen($email) > 1){
            
            $obj = new Ead_Model_DbTable_Usuarios();
            $result = $obj->fetchRow('USU_EMAIL like "'.$email.'"');

            if(isset($result->USU_EMAIL)){
                echo json_encode(array('ok' => FALSE,'msg'=>'E-mail '.$result->USU_EMAIL.' já existe!'));
            }
            else{
                echo json_encode(array('ok' => TRUE)); 
            }
        }
        else{
            echo json_encode(array('ok' => TRUE)); 
        }
        
    }
    
    public function valloginAction(){
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender(); 
        
        $login = $this->_getParam('login', FALSE);
        
        if($login != FALSE && strlen($login) > 1){
            $obj = new Ead_Model_DbTable_Usuarios();
            $result = $obj->fetchRow('USU_LOGIN like "'.$login.'"');

            if(isset($result->USU_LOGIN)){
                echo json_encode(array('ok' => FALSE,'msg'=>'Login '.$result->USU_LOGIN.' já existe!')); 
            }
            else{
                echo json_encode(array('ok' => TRUE));
            }
        }
        else{
            echo json_encode(array('ok' => TRUE)); 
        }
    }
    
    public function confirmarAction(){
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender(); 
        
        $user = $this->_getParam('user', FALSE);
        
        if($user != FALSE){
            
            $obj = new Ead_Model_DbTable_Usuarios();
            
            $res = $obj->fetchRow('USU_ID = "' . $user.'"');
            
            if(!isset($res->USU_LOGIN)){
                echo '<script>alert("Esse cadastro nao existe!"); location.href = "'.$this->_urlbase.'"; </script>';
                exit();
            }
            
            // update
            $obj->update(array('USU_STAEML'=>0),'USU_ID = '.$user);
            
            $res = $obj->fetchRow('USU_ID = "' . $user.'"');
            
            Zend_Loader::loadClass('auth','library');
            
            $login = $res->USU_LOGIN;
            $senha = '';

            $dbAdapter = Zend_Db_Table::getDefaultAdapter();
            //Inicia o adaptador Zend_Auth para banco de dados
            $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
            $authAdapter->setTableName('USUARIOS')
                    ->setIdentityColumn('USU_LOGIN')
                    ->setCredentialColumn('USU_LOGIN');// USU_SENHA
                    //->setCredentialTreatment('SHA1(?)');

            //Define os dados para processar o login
            $authAdapter->setIdentity($login)
                    ->setCredential($login);

            //Efetua o login
            $auth = Zend_Auth::getInstance();
            $result = $auth->authenticate($authAdapter);

            $info = $authAdapter->getResultRowObject(null, 'USU_LOGIN');
            $storage = $auth->getStorage();
            $storage->write($info);

            // valida status do usuário
             Zend_Loader::loadClass('usuario','library');
             if(!Usuario::ValidarStaUsu($storage->read()->USU_ID)){
                 //Dados inválidos
                 $this->_helper->FlashMessenger('Usuário ou senha inválidos!');
                 return $this->_helper->redirector('index', 'index', array());
             }

             Usuario::setIdSessaoUsu($storage->read()->USU_ID, session_id());

             auth::montaSessao($auth,$authAdapter);
            
            //echo '<script>alert("Cadastro confirmado com sucesso!"); location.href = "'.$this->_urlbase.'/'.$this->_modulo.'/meuscursos"; </script>';
             echo '<script>alert("Cadastro confirmado com sucesso!"); location.href = "'.$this->_urlbase.'/"; </script>';
             
        }else{
            echo '<script>alert("Usuário de Cadastro incorreto!"); location.href = "'.$this->_urlbase.'"; </script>';
        }
         
    }
     
}

